package com.aptech.forms.tdkhoa;

import com.aptech.beans.Users;
import com.aptech.dao.UserManager;
import com.aptech.utility.DBType;
import com.aptech.utility.DBUtil;
import com.aptech.validate.AccountValidator;
import java.awt.Frame;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.*;
import java.sql.*;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Vector;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.RowFilter;
import javax.swing.RowSorter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

public class CheckConnection extends javax.swing.JFrame {

    public CheckConnection() {
        initComponents();
        setLocationRelativeTo(null);
        toFront();
        setState(Frame.NORMAL);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jlblAccList_Username2 = new javax.swing.JLabel();
        jpwCheckConnection_Password = new javax.swing.JPasswordField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jtfCheckConnection_Username = new javax.swing.JTextField();
        jtfCheckConnection_Servername = new javax.swing.JTextField();
        jbtCheckConnection_Connect = new javax.swing.JButton();
        jbtLoginCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setIconImage(new ImageIcon(getClass().getResource("/com/image/icon.png")).getImage());
        setResizable(false);

        jLabel1.setFont(new java.awt.Font("Segoe UI Light", 1, 24)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(255, 0, 0));
        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/image/009.png"))); // NOI18N
        jLabel1.setText("Check Connection");

        jlblAccList_Username2.setFont(new java.awt.Font("Segoe UI Light", 1, 14)); // NOI18N
        jlblAccList_Username2.setForeground(new java.awt.Color(51, 0, 255));
        jlblAccList_Username2.setText("Server name");

        jpwCheckConnection_Password.setFont(new java.awt.Font("Segoe UI Light", 1, 14)); // NOI18N
        jpwCheckConnection_Password.setToolTipText("Typical your password");

        jLabel4.setFont(new java.awt.Font("Segoe UI Light", 1, 14)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(255, 0, 0));
        jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/image/002.png"))); // NOI18N
        jLabel4.setText("Password:");

        jLabel5.setFont(new java.awt.Font("Segoe UI Light", 1, 14)); // NOI18N
        jLabel5.setForeground(new java.awt.Color(255, 0, 0));
        jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/image/001.png"))); // NOI18N
        jLabel5.setText("Username:");

        jtfCheckConnection_Username.setFont(new java.awt.Font("Segoe UI Light", 1, 14)); // NOI18N
        jtfCheckConnection_Username.setForeground(new java.awt.Color(255, 0, 51));
        jtfCheckConnection_Username.setToolTipText("Typical your account");
        jtfCheckConnection_Username.setPreferredSize(new java.awt.Dimension(60, 20));

        jtfCheckConnection_Servername.setFont(new java.awt.Font("Segoe UI Light", 1, 14)); // NOI18N
        jtfCheckConnection_Servername.setForeground(new java.awt.Color(255, 0, 51));
        jtfCheckConnection_Servername.setToolTipText("Typical your account");
        jtfCheckConnection_Servername.setPreferredSize(new java.awt.Dimension(60, 20));

        jbtCheckConnection_Connect.setFont(new java.awt.Font("Segoe UI Light", 1, 14)); // NOI18N
        jbtCheckConnection_Connect.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/image/003.png"))); // NOI18N
        jbtCheckConnection_Connect.setMnemonic('S');
        jbtCheckConnection_Connect.setText("Connect");
        jbtCheckConnection_Connect.setToolTipText("Click here to login");
        jbtCheckConnection_Connect.setSelected(true);
        jbtCheckConnection_Connect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtCheckConnection_ConnectActionPerformed(evt);
            }
        });

        jbtLoginCancel.setFont(new java.awt.Font("Segoe UI Light", 1, 14)); // NOI18N
        jbtLoginCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/image/005.png"))); // NOI18N
        jbtLoginCancel.setMnemonic('C');
        jbtLoginCancel.setText("Cancel");
        jbtLoginCancel.setToolTipText("Click here to exit program");
        jbtLoginCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtLoginCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(55, 55, 55)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jlblAccList_Username2, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addGap(26, 26, 26)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jtfCheckConnection_Servername, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jtfCheckConnection_Username, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jpwCheckConnection_Password, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(91, 91, 91)
                        .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 367, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(92, 92, 92)
                .addComponent(jbtCheckConnection_Connect)
                .addGap(27, 27, 27)
                .addComponent(jbtLoginCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlblAccList_Username2)
                    .addComponent(jtfCheckConnection_Servername, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jtfCheckConnection_Username, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jpwCheckConnection_Password, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(31, 31, 31)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jbtCheckConnection_Connect, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jbtLoginCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(31, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbtCheckConnection_ConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtCheckConnection_ConnectActionPerformed
        String serverName = jtfCheckConnection_Servername.getText().trim();
        String userName = jtfCheckConnection_Username.getText().trim();
        String password = String.valueOf(jpwCheckConnection_Password.getPassword());
        if (checkConnection(serverName, userName, password)) {
            new Login().setVisible(true);
        }
    }//GEN-LAST:event_jbtCheckConnection_ConnectActionPerformed

    private void jbtLoginCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtLoginCancelActionPerformed
        this.dispose();
    }//GEN-LAST:event_jbtLoginCancelActionPerformed

    // ****CheckConnection method****
    private boolean checkConnection(String ServerName, String UserName, String Password) {
        try {
            String connectionString = "jdbc:sqlserver://" + ServerName + ";databaseName=MedicalDB;user=" + UserName
                    + ";password=" + Password + ";";
            System.out.println(connectionString);
            Connection conn = DriverManager.getConnection(connectionString);
            if (conn != null) {
                // store connection string to properties file
                Properties prop = new Properties();
                try (InputStream inputStream = DBUtil.class.getClassLoader().getResourceAsStream("com/aptech/utility/db.properties")) {
                    prop.load(inputStream);
                    prop.setProperty("myConnection", connectionString);
                }
//                DBUtil.class.getClassLoader().getResourceAsStream("com/aptech/utility/db.properties");
                OutputStream output = new FileOutputStream(new File("src\\com\\aptech\\utility\\db.properties"));
                prop.store(output, null);
                output.close();
                return true;
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Connection failed\nTry again", "Connection error", JOptionPane.ERROR_MESSAGE);
        } catch (IOException ex) {
            Logger.getLogger(CheckConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;

                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CheckConnection.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CheckConnection.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CheckConnection.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CheckConnection.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new CheckConnection().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JButton jbtCheckConnection_Connect;
    private javax.swing.JButton jbtLoginCancel;
    private javax.swing.JLabel jlblAccList_Username2;
    private javax.swing.JPasswordField jpwCheckConnection_Password;
    private javax.swing.JTextField jtfCheckConnection_Servername;
    private javax.swing.JTextField jtfCheckConnection_Username;
    // End of variables declaration//GEN-END:variables
    private String flag = "";
    DefaultTableModel tableModel;
}
